package pkg.andru.animation;

import java.util.ArrayList;
import java.util.List;

import pkg.andru.animation.Frame.FrameDrawState;
import android.graphics.Canvas;

public class Anime implements IDrawable<AnimeDrawState> {

    static final String TAG = "Anime";

    private int id;
    private String name;

    private List<FrameWrapper> mFrames;

    public Anime() {
        mFrames = new ArrayList<FrameWrapper>();
        mFrames.clear();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void addFrame(Frame frame, FrameDrawState state) {
        final FrameWrapper wrapper = new FrameWrapper();
        wrapper.frame = frame;
        wrapper.drawState = state;

        mFrames.add(wrapper);
    }

    public Frame getFrame(int position) {
        return mFrames.get(position).frame;
    }

    public int getFrameCount() {
        return mFrames.size();
    }

    int getFrameDuration(int index) {
        final FrameWrapper wrapper = mFrames.get(index);
        return wrapper.drawState.getDuration();
    }

    @Override
    public String toString() {
        return "Anime [id=" + id + ", name=" + name + ", mFrames=" + mFrames + ", getFrameCount()=" + getFrameCount() + "]";
    }

    class FrameWrapper {
        Frame frame;
        FrameDrawState drawState;

        @Override
        public String toString() {
            return "FrameWrapper [frame=" + frame.toString() + ", drawState=" + drawState.toString() + "]";
        }
    }

    @Override
    public void onDraw(Canvas canvas, AnimeDrawState state) {
        final int size = mFrames.size();
        final int index = state.getFrameIndex();
        if (index != -1 && index < size) {
            float x = state.getPx();
            float y = state.getPy();
            for (int i = 0; i <= index; i++) {
                final FrameWrapper wrapper = mFrames.get(i);
                if (wrapper.drawState.isKeeped() || i == index) {
                    wrapper.drawState.updatePosition(x, y);
                    wrapper.frame.onDraw(canvas, wrapper.drawState);
                }
            }
        }
    }
}
